package amani.wechat.platform.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * HttpServletRequest 的工具类
 * 
 * @author VV
 *
 */
public class HttpRequestUtils {
	/**
	 * 读取请求内容
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static String ReadRequestContent(HttpServletRequest request)
			throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(
				request.getInputStream()));
		StringBuilder sb = new StringBuilder();
		String xmlHead = "";
		String xmlContent = "";
		String line = null; 
			while ((line = in.readLine()) != null) {
				sb.append(line);
			} 
		return sb.toString(); 
	}
	
	/**
	 * 获取cookie值
	 * @param request
	 * @param key
	 * @return
	 */
	public static String GetCookieValue(HttpServletRequest request ,String key){
		Cookie[] cookies=request.getCookies();
		if(cookies!=null){
			for (int i = 0; i < cookies.length; i++) {
				if(cookies[i].getName().equals(key)){
					return cookies[i].getValue();
				}
			}
		}
		return "";
	}
	
	/**
	 * 获取客户端ip
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
